package com.langsin.my0628;

import com.langsin.bean.User;
import com.langsin.wanghongxiang.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;

public class WhxTest {
    //二级缓存需要我们的对象能序列化，二级缓存有可能存入到硬盘里的
    @Test
    public void testCache2()throws Exception{
        //mybatis一级缓存是存在sqlSession的内存map里的
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = builder.build(stream);
        SqlSession sqlSession1 = sessionFactory.openSession();
        //第一个会话的查询
        UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
        User user1 = mapper1.queryById(702);
        System.out.println(user1);
        sqlSession1.close();

        Thread.sleep(2000);
        System.out.println("休眠2s时间到！");

        //第二个会话
        SqlSession sqlSession2 = sessionFactory.openSession();
        UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
        User user2 = mapper2.queryById(702);
        System.out.println(user2);
        sqlSession2.close();
    }
    @Test
    public void testCache1() throws Exception {
         //mybatis一级缓存是存在sqlSession的内存map里的
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = builder.build(stream);
        SqlSession sqlSession = sessionFactory.openSession();
        //查询第一次
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.queryById(702);
        System.out.println(user);
        Thread.sleep(2000);

        //查询第二次
        User user1 = mapper.queryById(702);
        System.out.println(user1);
        //如果同一个会话对象进行了增删改，缓存就会失效


    }
}
